// buildValidator.ts
import { validatorPool } from '@/utils/validatorPool';

export function buildValidator(ruleObj: any) {
  return (_: any, value: any, cb: Function) => {
    const val = value === null || value === undefined ? '' : String(value).trim();
 
    // 1. 必填
    if (ruleObj.required && !val) {
      return cb(new Error(`${ruleObj.fieldName}不能为空`));
    }
    if (!ruleObj.required && !val) return cb();



    // 3. 通用规则
    const len = val.length;
    if (ruleObj.min !== undefined && len < ruleObj.min) {
      return cb(new Error(`长度不能小于 ${ruleObj.min}`));
    }
    if (ruleObj.max !== undefined && len > ruleObj.max) {
      return cb(new Error(`长度不能超过 ${ruleObj.max}`));
    }
    if (ruleObj.numeric) {
      const n = Number(val);
      if (isNaN(n)) return cb(new Error('必须是数字'));
      if (ruleObj.min !== undefined && n < ruleObj.min) return cb(new Error(`不能小于 ${ruleObj.min}`));
      if (ruleObj.max !== undefined && n > ruleObj.max) return cb(new Error(`不能大于 ${ruleObj.max}`));
    }
        // 2. 自定义函数（白名单）
    if (ruleObj.custFunction) {
      const fn = validatorPool[ruleObj.custFunction];
    
      if (!fn) return cb(new Error(`未知函数 ${ruleObj.custFunction}`));
      return fn(_, val, cb);
    }
    cb();
  };
}
